package gro.ecorrdata.edata.controller;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;

import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import gro.ecorrdata.edata.annotation.NoneAuth;
import gro.ecorrdata.edata.model.BaseResponse;
import gro.ecorrdata.edata.util.CodeUtil;

/**
 * Captcha by huwhois time 2019/11/22
 */
@RestController
@RequestMapping("/captcha")
public class Captcha {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // @CrossOrigin
    // 创建文件输出流对象
    @NoneAuth
    @RequestMapping("/captcha_src")
    public BaseResponse<Map<String, Object>> getCaptchaSrc(){
        Map<String, Object> map = CodeUtil.generateCodeAndPic();

        String sql = "INSERT INTO verify(`uuid`, `code`) VALUES(?,?)";
        String uuid = UUID.randomUUID().toString().replace("-", "");
        Object args[] = {uuid, map.get("code")};
        Integer temp = jdbcTemplate.update(sql, args);
        if (temp > 0) {
            System.out.println(map.get("code"));
        }
        
        // response.reset();
        // // 设置response的Header
        // // response.addHeader("Content-Length", "" + file.length());
        // response.setContentType("image/jpg");

        BufferedImage image = (BufferedImage) map.get("codePic");
        // 将图片转正base64
        // 转base64
        try {
            BASE64Encoder encoder = new BASE64Encoder();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
            ImageIO.write(image, "jpg", baos);//写入流中
            byte[] bytes = baos.toByteArray();//转换成字节
            String png_base64 =  encoder.encodeBuffer(bytes).trim();//转换成base64串
            //删除 \r\n
            png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");
            baos.close();
    
    
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("base64","data:image/png;base64,"+ png_base64);
            result.put("codeuid", uuid);
            return new BaseResponse<>(true, "验证码获取成功", result);
        } catch (Exception e) {
            return new BaseResponse<>(true, "验证码获取失败", null);
        }
    }
}
